import React, { useEffect, useState } from 'react';
import { View, Text, Button, TouchableOpacity, StyleSheet, FlatList, Modal } from 'react-native';
import { Divider } from '@rneui/base';
import { CommonStyle } from '../common/commonStyle.ts';
import Tools from '../utils/Tools.ts';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import EmptyCom from './Empty.tsx';
import AntDesign from 'react-native-vector-icons/AntDesign';

export interface TreeNode {
  name: string;
  id: number;
  levels?: number;
  flag?: boolean;
  parentId?: number;
  children?: TreeNode[];
}

interface CascaderProps {
  levels: number; //1 只能多选或单选“楼”  2只能单选“楼”但可多选/单选“单元” 3只能单选“楼、单元”但可多选“层” 4只能单选“楼、单元、层,可多选"门牌号"
  title?: string;
  show: boolean;
  data: TreeNode[];
  selectedIds?: number[];
  onChange?: (selectedValues: TreeNode[], ids: number[]) => void;
  onClose: () => void;
  onConfirm: (selectedValues: TreeNode[], ids: number[]) => void;
  closeOnClickOverlay?: boolean;
}

const CascadingPickerSelect: React.FC<CascaderProps> = ({ data, closeOnClickOverlay, title, onChange, selectedIds, show, onClose, onConfirm, levels }) => {
  const [isModalVisible, setModalVisible] = useState(false);
  const [selected, setSelected] = useState<TreeNode[]>([]);
  const [buildId, setBuildId] = useState<number>(0);
  const [unitId, setUnitId] = useState<number>(0);

  useEffect(() => {
    // 监听data有值的时候 并且selectedIds有返回值，并且selected等于0
    //需要将selectedIds中的id 与data里id相等的对象的flag设置为true
    if (data && selectedIds && selected.length === 0) {
      // selectedIds.forEach((item) => {
      //   setSelected((prevState) => prevState.concat(Tools.findTreeNodeById(data, item)));
      // });
    }
  }, []);

  useEffect(() => {
    setModalVisible(show);
  }, [show]);

  useEffect(() => {
    if (selectedIds?.length === 0) {
      setSelected([]);
    }
  }, [selectedIds]);

  // useEffect(() => {
  //   const transformedData = getTrueFlags(selected);
  //   onConfirm && onConfirm(
  //     transformedData,
  //     transformedData.map((c) => c.id),
  //   );
  // }, [selected]);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
    onClose();
  };

  const handleSelect = (item: TreeNode) => {
    if (item.levels! < levels) {
      // 一旦当前点击的level级别小于传过来levels 就只能单选
      // 如果栋单选，那么切换之后当前栋下面的所有单元、层、门牌号全部flag为false，
      // 如果单元单选，那么切换之后当前单元下面的所有层、门牌号 flag全部为false，
      // 如果层单选，那么切换之后当前单元下面的所有门牌号 flag全部为false
      //data里面包含所有栋 所有单元 所有层 所有门牌号信息
      item.flag = true;
      // switch (item.levels) {
      //   case 1:
      //     setBuildId(item.id)
      //     for (let d in data) {
      //       if (data[d].id !== item.id) {
      //         data[d].flag = false;
      //       }
      //     }
      //     if(item.children!.length>0){
      //       for(let dy of item.children!){
      //         dy.flag= false
      //        if(dy.children!.length>0){
      //         for(let c of dy.children!){
      //           c.flag =false
      //           if(c.children!.length>0){
      //             for(let mph of c.children!){
      //               mph.flag = false
      //             }
      //           }
      //         }

      //        }
      //       }
      //     }
      //     break;

      //   case 2:
      //     setUnitId(item.id)
      //     for(let d in data){
      //       if(data[d].id === item.parentId){
      //         for(let dy of data[d].children!){
      //           if(dy.id!==item.id){
      //             dy.flag = false
      //           }
      //         }
      //       }
      //     }
      //     if(item.children!.length>0){
      //         for(let c of item.children!){
      //           c.flag =false
      //           if(c.children!.length>0){
      //             for(let mph of c.children!){
      //               mph.flag = false
      //             }
      //           }
      //         }
      //     }
      //     break;
      //   case 3:
      //     //这一层要拿栋id
      //     for(let d in data){
      //       if(data[d].id === buildId){
      //         if(data[d].children!.length>0){
      //           for(let dy of data[d].children!){
      //             if(dy.id===unitId && dy.children!.length>0){
      //               for(let c of dy.children!){
      //                 if(c.id !== item.id){
      //                   c.flag =false
      //                 }
      //                 if(c.children!.length>0){
      //                   for(let mph of c.children!){
      //                     mph.flag = false
      //                   }
      //                 }
      //               }
      //             }
      //           }
      //         }
      //       }
      //     }
      //     break;
      // }
      switch (item.levels) {
        case 1:
          setBuildId(item.id);
          setFlagRecursively(data, null); // 清除所有节点的标志
          item.flag = true; // 只标记当前节点
          break;

        case 2:
          setUnitId(item.id);
          const parentNode = data.find((d) => d.id === item.parentId);
          if (parentNode) {
            setFlagRecursively(parentNode.children || [], item.id); // 只标记当前单位节点
          }
          break;

        case 3:
          const buildingNode = data.find((d) => d.id === buildId);
          if (buildingNode) {
            const unitNode = buildingNode.children?.find((dy) => dy.id === unitId);
            if (unitNode) {
              setFlagRecursively(unitNode.children || [], item.id); // 只标记当前栋节点
            }
          }
          break;
      }

      let lock = false;
      selected.forEach((item) => {
        if (!item.children) lock = true;
      });
      if (!lock) {
        setSelected((prevState) => {
          return prevState.concat(item);
        });
      } else {
        // 替换最后一位
        setSelected((prevArray) => {
          return prevArray.map((prev, index) => (index === prevArray.length - 1 ? item : prev));
        });
      }
    } else {
      item.flag = !item.flag;
      if (levels === 1 && item.levels === 1) {
        //需要保存楼栋的数据
        setSelected((prevState) => {
          return prevState.concat(item);
        });
        setTimeout(() => {
          console.log(selected, 'aaa');
        }, 2000);
      }
    }
    if (!item.children) {
      toggleModal();
    }
  };

  const setFlagRecursively = (nodes: TreeNode[], itemId: number | null) => {
    for (const node of nodes) {
      node.flag = node.id === itemId; // 只标记选中的节点为 true
      if (node.children) {
        setFlagRecursively(node.children, itemId); // 递归调用处理子节点
      }
    }
  };

  const handleTabClick = (item: TreeNode, index: number) => {
    setSelected((prevArray) => prevArray.slice(0, index));
  };

  const getTrueFlags = (data: TreeNode[]) => {
    const trueFlags: TreeNode[] = [];
    const uniqueFlags: TreeNode[] = []; // 用于存放去重后的结果

    function recursiveCheck(obj: TreeNode) {
      if (obj.flag === true && !uniqueFlags.some((item) => item.id === obj.id)) {
        trueFlags.push(obj);
        uniqueFlags.push(obj);
      }

      if (obj.children && obj.children.length > 0) {
        for (let i = 0; i < obj.children.length; i++) {
          recursiveCheck(obj.children[i]);
        }
      }
    }

    const copiedData = JSON.parse(JSON.stringify(data));

    for (let i = 0; i < copiedData.length; i++) {
      recursiveCheck(copiedData[i]);
    }

    // function filterByLevels(uniqueFlags:TreeNode[],levels:number) {
    //   return uniqueFlags.filter(obj => obj.levels === levels);
    // }  filterByLevels(uniqueFlags,levels);

    return uniqueFlags;
  };

  const renderTab = () => (
    <View style={styles.tabContainer}>
      {selected.length > 0 ? (
        selected.map((item, index) => {
          return (
            <TouchableOpacity key={index} onPress={() => handleTabClick(item, index)}>
              <Text style={styles.tabText}>{levels !== 1 ? item.name || '请选择' : index === 0 ? `${item.name}[${selected.length}]` : ''}</Text>
            </TouchableOpacity>
          );
        })
      ) : (
        <TouchableOpacity onPress={() => {}}>
          <Text style={styles.tabText}>{'请选择'}</Text>
        </TouchableOpacity>
      )}
    </View>
  );

  const renderList = (data: TreeNode[]) => (
    <FlatList
      data={levels === 1 ? data : selected.length === 0 ? data : selected[selected.length - 1].children ? selected[selected.length - 1].children : selected[selected.length - 2].children}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item, index }) => (
        <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => handleSelect(item)} key={index}>
          <View>
            <Text style={styles.listItem}>{item.name}</Text>
          </View>
          <View>{item.flag && <AntDesign name="check" size={16} color={CommonStyle.mainColor}></AntDesign>}</View>
        </TouchableOpacity>
      )}
      ListEmptyComponent={
        <View style={{ height: 300 }}>
          <EmptyCom text={'已经选完了'} />
        </View>
      }
    />
  );

  const handleCascaderConfirm = () => {
    const transformedData = getTrueFlags(selected);
    onConfirm(
      transformedData,
      transformedData.map((c) => c.id),
    );
  };

  return (
    <>
      <Modal visible={isModalVisible} transparent animationType="fade">
        <View style={styles.container}>
          <Touchable
            style={styles.touchArea}
            onPress={() => {
              closeOnClickOverlay ? onClose() : undefined;
            }}
          >
            <View></View>
          </Touchable>
          <View style={styles.pickerContainer}>
            {/* 标题和按钮 */}
            <View style={styles.header}>
              <TouchableOpacity onPress={onClose}>
                <Text style={(styles.button, { color: '#969799' })}>取消</Text>
              </TouchableOpacity>
              <Text style={styles.title}>{title}</Text>
              <TouchableOpacity onPress={handleCascaderConfirm}>
                <Text style={styles.button}>确认</Text>
              </TouchableOpacity>
            </View>

            <View style={styles.pickerContent}>
              {renderTab()}
              {renderList(data)}
            </View>
          </View>
        </View>
      </Modal>
    </>
  );
};

export default CascadingPickerSelect;

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.2)' },
  touchArea: { flex: 1, backgroundColor: 'rgba(0,0,0,0.2)' },
  pickerContainer: { backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingBottom: 20 },
  header: { flexDirection: 'row', justifyContent: 'space-between', padding: 15, borderBottomWidth: 1, borderBottomColor: '#ddd' },
  title: { fontSize: 16, fontWeight: 'bold' },
  button: { fontSize: 14, color: '#333333' },
  pickerContent: { position: 'relative', height: 350, justifyContent: 'center', paddingHorizontal: 16 },

  tabContainer: { flexDirection: 'row', marginVertical: 10 },
  tabText: { marginRight: 10, fontSize: 14, color: CommonStyle.mainColor },
  activeTabText: { color: CommonStyle.mainColor, paddingVertical: 10, fontSize: 13 },
  listItem: { paddingVertical: 10, fontSize: 14, color: '#333' },
});
